# -*- coding: utf-8 -*-
from odoo import api, fields, models


class SLSaleOrder(models.Model):
    _inherit = 'sale.order'

    SL_invoice_total = fields.Float(string='已開發票金額', compute='compute_sl_invoice_total', store=True)
    SL_paid_total = fields.Float(string='已收款金額', compute='compute_sl_invoice_total', store=True)
    SL_unpaid_total = fields.Float(string='剩餘應收金額', compute='compute_sl_invoice_total', store=True)
    Shipping_address = fields.Char(string='收貨地址', related='partner_shipping_id.street', store=True)
    # 需要將 invoice_ids 設定為資料庫有的紀錄
    invoice_ids = fields.Many2many(store=True)
    # 當客戶id改變時，自動套用塞選顯示該客戶名稱底下的地址
    @api.multi
    @api.onchange('partner_shipping_id', 'partner_id')
    def onchange_partner_shipping_id(self):
        res = super(SLSaleOrder, self).onchange_partner_shipping_id()
        if self.partner_id:
            name = self.partner_id.name
            return {
                'domain': {
                    'partner_shipping_id': ['|', ('name', 'like', name), ('parent_id', '=', self.partner_id.id)],
                    'partner_invoice_id': ['|', ('name', 'like', name), ('parent_id', '=', self.partner_id.id)],
                }
            }
        return res
    # 更新觸發條件
    @api.depends('invoice_ids.residual')
    def compute_sl_invoice_total(self):
        for line in self:
            if len(line.invoice_ids) < 1 :
                return True
            total = 0.0
            unpaid = 0.0
            uncheck_invoice = 0.0
            for row in line.invoice_ids:
                total += row.amount_total_signed
                if row.state == 'open' or row.state == 'paid':
                    unpaid += row.residual_signed
                elif row.state == 'draft':
                    uncheck_invoice += row.amount_total_signed
            # total 為已開發票的總額
            # unpaid 為已開發票中，剩餘多少應付
            # uncheck_invoice 為草稿發票
            # SL_unpaid_total 為 (已開發票未付款 + 草稿發票 + 未開發票金額)
            line.SL_invoice_total = total
            line.SL_paid_total = total - unpaid - uncheck_invoice
            line.SL_unpaid_total = unpaid + uncheck_invoice + line.amount_total - total

    def update_sl_order_and_invoice(self):
        for line in self.search([]):
            total = 0.0
            unpaid = 0.0
            uncheck_invoice = 0.0
            for row in line.invoice_ids:
                total += row.amount_total_signed
                if row.state == 'open' or row.state == 'paid':
                    unpaid += row.residual_signed
                elif row.state == 'draft':
                    uncheck_invoice += row.amount_total_signed
            line.invoice_total = total
            line.paid_total = total - unpaid - uncheck_invoice
            line.unpaid_total = unpaid + uncheck_invoice + line.amount_total - total


class SLSaleOrderLine(models.Model):
    _inherit = 'sale.order.line'

    qty_delivered_total = fields.Float(string='已出貨總額', compute='compute_del_total', store=True)
    qty_to_delivered = fields.Float(string='待出貨', compute='compute_to_delivered', store=True)
    order_date = fields.Datetime(string='下單日期', related='order_id.date_order', store=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, index=True)

    @api.depends('qty_delivered', 'product_uom_qty')
    def compute_to_delivered(self):
        for line in self:
            line.qty_to_delivered = line.product_uom_qty - line.qty_delivered

    @api.depends('price_unit', 'qty_delivered')
    def compute_del_total(self):
        for line in self:
            line.qty_delivered_total = line.qty_delivered * line.price_unit
